/*
 * Engine.c
 *
 * Created: 20/03/2012 12:45:35
 *  Author: Dani
 */ 

#include <avr/io.h>
#include <avr/interrupt.h>
#include "engine.h"

#define ENGINE_HIGH 1
#define ENGINE_LOW 0

uint8_t speed;
uint8_t engine_status;
uint8_t engine_pwm;

// If the product in the container is new and the the tube is empty,
void EngineProcutChange(uint8_t product)
{
}

void EngineInit()
{
	//Engine Ports as output (PA.3 - PA.7)
	ENGINE_DDR |= 0b11111000;
	
	//Timer 0 in Normal Mode, prescaling = 64.
	TCCR0 |= 0b00000011;
}

void EnginePWMEnable(uint8_t enable)
{
	if (enable)
		//Timer0 Interrupt enable
		TIMSK |= 0b00000001;
	else
		//Timer0 Interrupt disable
		TIMSK &= ~(0b00000001);
}

void EngineControl(uint8_t engine_num, uint8_t engine_speed)
{
	switch (engine_speed)
	{
		case 0:
			// Switch off the motor
			EnginePWMEnable(0);
			ENGINE_PORT &= ~ engine_num;	
			break;
		case 255:
			// Switch on the motor, max speed.
			EnginePWMEnable(0);
			ENGINE_PORT |= engine_num;	
			break;
		default:
			// PWM mode
			EnginePWMEnable(1);
			engine_pwm = engine_num;
			speed = engine_speed;	
	}	
}

ISR(TIMER0_OVF_vect)
{
	// Toggle the engine output
	// High time: 255 - "speed"; Low time: "speed".
	if (engine_status == ENGINE_LOW)
	{
		TCNT0 = 255 - speed;
		engine_status = ENGINE_HIGH;
		ENGINE_PORT |= engine_pwm;		
	} 
	else
	{
		TCNT0 = speed;
		engine_status = ENGINE_LOW;
		ENGINE_PORT &= ~engine_pwm;	
	}	
}